<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 * @version		$Id: Mail.php 108 2011-04-11 17:33:46Z ninhgio@gmail.com $
 */

class Modules_Mail_Services_Mail
{
	/**
	 * Get mail server configurations
	 * 
	 * @return array
	 */
	public static function getConfig()
	{
		return Gio_Core_Module::getConfig('mail', true);
	}
	
	/**
	 * Save mail server configurations
	 * 
	 * @param array $data
	 */
	public static function saveConfig($data)
	{
		$config   = self::getConfig();
		
		$protocol = $data['protocol']['protocol'];
		$config['protocol']['protocol'] = $protocol;
		
		switch ($protocol) {
			case 'mail':
				if (isset($config['smtp'])) {
					unset($config['smtp']);
				}
				break;
			case 'smtp':
				$host = $data['smtp']['host'];
				if ($host == null || $host == '') {
					unset($config['smtp']['host']);
				} else {
					$config['smtp']['host'] = $host;
				}
				
				$port = $data['smtp']['port'];
				if ($port == null || $port == '') {
					unset($config['smtp']['port']);
				} else {
					$config['smtp']['port'] = $port;
				}
				
				if ($data['authentication'] == 'true') {
					$config['smtp']['username'] = $data['smtp']['username'];
					$config['smtp']['password'] = $data['smtp']['password'];
				} else {
					unset($config['smtp']['username']);
					unset($config['smtp']['password']);
				}
				
				$security = $data['smtp']['security'];
				if ($security != 'none') {
					$config['smtp']['security'] = $security;
				}
				break;
		}
		$content = Gio_Core_Array::toIni($config, true);
		/**
		 * Write file
		 */
		$fileName = MOD_DIR .DS . 'mail' . DS . 'configs' . DS . 'config.ini';
		return Gio_Core_File::writeToFile($fileName, $content);
	}
	
	public static function getMails($userId, $offset = null, $count = null)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Mail_Models_Mysql_Mail();
		$dao->setDbConnection($conn);
		return $dao->getMails($userId, $offset, $count);
	}
	
	public static function count($userId)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Mail_Models_Mysql_Mail();
		$dao->setDbConnection($conn);
		return $dao->count($userId);
	}
	
	public static function add($mail)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao = new Modules_Mail_Models_Mysql_Mail();
		$dao->setDbConnection($conn);
		return $dao->add($mail);
	}
}
